package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.admin.service.AdUserService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.dtos.ChannelDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private AdUserMapper adUserMapper;

    @Override
    public ResponseResult login(AdUserDto dto) {
        // 1.参数校验
        if (null == dto || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或者密码不能为空！");
        }
        // 2.根据name查询用户信息
        LambdaQueryWrapper<AdUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdUser::getName, dto.getName());
        List<AdUser> adUserList = this.list(lambdaQueryWrapper);
        if (null == adUserList || adUserList.size() != 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名不存在！");
        }
        // 3.将用户传过来的password加上salt，进行md5加密，和数据库的密文密码进行比对
        AdUser adUser = adUserList.get(0);

        String md5Password = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        if (!adUser.getPassword().equals(md5Password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 4.生成token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        // 5.如果是成功的，将user、token返回
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("token", token);
        adUser.setSalt("");
        adUser.setPassword("");
        resultMap.put("user", adUser);
        return ResponseResult.okResult(resultMap);
    }
}
